// pages/RankingList/RankingList.js
var util = require('../../utils/util.js')

const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        currentTab: 0,
        avatarUrl: '/image/pc_20.png',
        nikename: "未登录",
        checkpoint: 0,
        FriendsRankings: [],
        WorldRankings: [],
        FriendsRank: '0',
        WorldRank: '0'
    },
    RankTypeTap: function (e) {
        var that = this;
        var newId = e.currentTarget.dataset.id;
        if (this.data.currentTab == newId) {
            return false;
        } else {
            that.setData({
                currentTab: newId
            })
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        console.log(options, app.globalData.userInfo)
        var that = this;
        wx.getStorage({
            key: 'userInfo',
            success: function (res) {
                console.log('local', res)
                var userInfo = JSON.parse(res.data)
                console.log('5454554', res.data)
                that.setData({
                    avatarUrl: userInfo.avatarUrl,
                    nikename: userInfo.nickName,
                    checkpoint: userInfo.checkpoint,
                    token: userInfo.token,
                    group_id: userInfo.group_id

                })
                that.getAll_rank();
                that.rankList();
            },
            fail: function (res) {
                console.log(res)
                that.getAll_rank();
            }
        })
        /*if (app.globalData.userInfo) {
            this.setData({
                //   avatarUrl:app.globalData.userInfo.avatarUrl,
                nikename: app.globalData.userInfo.nickName,
                checkpoint: app.globalData.userInfo.checkpoint,
                token: app.globalData.userInfo.token,
                avatarUrl: app.globalData.userInfo.avatarUrl
            })
            //   wx.getStorage({
            //       key:'userInfo',
            //       success:function(res){
            //           var userInfo = JSON.parse(res.data)
            //             that.setData({
            //                 avatarUrl:userInfo.avatarUrl
            //             })
            //       }
            //   })
        }*/
        // for (let i = 0; i <10; i++) {
        /*setTimeout(function () {
            wx.getSavedFileList({
                success: function (res) {
                    if (res.fileList[0]) {
                        that.setData({
                            avatarUrl: res.fileList[0].filePath
                        })
                    }

                }
            })
        }, 200)*/
        // }

    },
    getAll_rank:function () {
        var that = this;
        console.log(that.data.token)
        wx.request({
            url: 'https://caige1.sanliwenhua.com/caige101/all_rank',
            method: "get",
            data: {
                x_token: that.data.token ? that.data.token : ''
            },
            success: function (res) {
                console.log(res)
                if (res.data.code == 200) {
                    that.setData({
                        WorldRank: res.data.data.my
                    })
                    var data = res.data.data.data;
                    console.log(data)
                    var WorldRankings = [];
                    for (var i = 0; i < data.length; i++) {
                        var WorldRankingsData = {}
                        WorldRankingsData.ranking = i + 1;
                        WorldRankingsData.userAvatar = data[i].avatar;
                        WorldRankingsData.userName = data[i].nickname;
                        WorldRankingsData.ShutDown = data[i].checkpoint;
                        WorldRankings.push(WorldRankingsData)
                    }
                    that.setData({
                        WorldRankings: WorldRankings
                    })
                    console.log(WorldRankings)

                } else {

                }
            },
            fail: function (res) {

            }
        })
    },
    rankList: function () {
        var that = this;
        console.log(that.data.token)
            console.log('caige1.sanliwenhua.com/rank',that.data.group_id, app.globalData.group_id, 'token', that.data.token, 'token_g', app.globalData.userInfo.token)

            function getMyList() {
                wx.request({
                    url: 'https://caige1.sanliwenhua.com/caige101/rank',
                    method: "get",
                    data: {
                        x_token: that.data.token ? that.data.token : '',
                        group_id: app.globalData.group_id
                    },
                    success: function (res) {
                        console.log('用戶獲取自己群內的信息', res)
                        if (res.data.code == 200) {
                            var data = res.data.data.data;
                            console.log(data)
                            var FriendsRankings = [];
                            for (var i = 0; i < data.length; i++) {
                                var FriendsRankingsData = {}
                                FriendsRankingsData.ranking = i + 1;
                                FriendsRankingsData.userAvatar = data[i].avatar;
                                FriendsRankingsData.userName = data[i].nickname;
                                FriendsRankingsData.ShutDown = data[i].checkpoint;
                                FriendsRankings.push(FriendsRankingsData)
                            }
                            that.setData({
                                FriendsRank: res.data.data.my,
                                FriendsRankings: FriendsRankings
                            })
                            console.log(FriendsRankings)

                        } else {

                        }
                    },
                    fail: function (res) {

                    }
                })
            }
            that.timeClock = setInterval(function () {
                if (app.globalData.userInfo && app.globalData.userInfo.token && app.globalData.group_id) {
                    console.log('獲取用戶信息')
                    getMyList()
                    clearInterval(that.timeClock)
                } else {
                    console.log('獲取到token后，獲取用戶信息')
                }
            }, 600)

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        if (app.globalData.userInfo && app.globalData.userInfo.token) {
            //this.login()
        }
    },
    login: function () {
        var that = this;
        wx.getUserInfo({
            success: function (res1) {
                console.log(res1)
                wx.login({
                    success: function (res) {
                        app.globalData.code = res.code;
                        console.log(app.globalData.code)
                        // 发送 res.code 到后台换取 openId, sessionKey, unionId
                        var dataSend = {
                            code: app.globalData.code,
                            encryptedData: res1.encryptedData,
                            iv: res1.iv,
                            icon: res1.userInfo.avatarUrl,
                            nickname: res1.userInfo.nickName
                        }
                        console.log('dataSend', dataSend)
                        wx.request({
                            url: 'https://caige1.sanliwenhua.com/caige101/wx/onLogin',
                            method: "get",
                            data: {
                                code: app.globalData.code,
                                encryptedData: res1.encryptedData,
                                iv: res1.iv,
                                icon: res1.userInfo.avatarUrl,
                                nickname: res1.userInfo.nickName
                            },
                            success: function (res3) {
                                console.log(res3)
                                if (res3.data.code == 200) {
                                    // app.globalData.Sharing = {}
                                    app.globalData.userInfo.token = res3.data.data.x_token;
                                    app.globalData.userInfo.checkpoint = res3.data.data.checkpoint;
                                    app.globalData.userInfo.id = res3.data.data.id;
                                    app.globalData.session_key = res3.data.data.session_key;
                                    wx.setStorage({
                                        key: 'checkpoint',
                                        data: res3.data.data.checkpoint
                                    })
                                    that.setData({
                                        checkpoint: res3.data.data.checkpoint
                                    })
                                    console.log(app.globalData);
                                    that.setData({
                                        userInfo: app.globalData.userInfo,
                                        hasUserInfo: true,
                                        // avatarUrl:res.userInfo.avatarUrl,
                                        nickName: res1.userInfo.nickName
                                    })
                                    // try {
                                    //     var userInfoStr = wx.getStorageSync('userInfo')
                                    //     var userInfoJson = JSON.parse(userInfoStr)
                                    //     if (userInfoStr) {
                                    //         that.setData({
                                    //             avatarUrl : userInfoJson.avatarUrl
                                    //         })
                                    //         // Do something with return value
                                    //     }
                                    //   } catch (e) {
                                    //     // Do something when catch error
                                    //   }

                                    wx.getStorage({
                                        key: 'userInfo',
                                        success: function (res) {
                                            console.log(res.data)
                                            var userInfoLocal = {}
                                            userInfoLocal = JSON.parse(res.data)
                                            console.log(userInfoLocal)
                                            userInfoLocal.token = res3.data.data.x_token;
                                            userInfoLocal.checkpoint = res3.data.data.checkpoint;
                                            userInfoLocal.token = res3.data.data.x_token;
                                            userInfoLocal.checkpoint = res3.data.data.checkpoint;
                                            wx.setStorage({
                                                key: 'userInfo',
                                                data: JSON.stringify(userInfoLocal)
                                            })
                                        },
                                        fail: function () {

                                        }
                                    })
                                    //分享次数缓存
                                    var mytime = new Date()
                                    var getFullYear = mytime.getFullYear().toString()
                                    var getMonth = (mytime.getMonth() + 1).toString()
                                    if (getMonth < 10) {
                                        getMonth = "0" + (mytime.getMonth() + 1).toString()
                                    }
                                    var getDate = mytime.getDate().toString()
                                    if (getDate < 10) {
                                        getDate = "0" + (mytime.getDate()).toString()
                                    }
                                    var date = getFullYear + getMonth + getDate
                                    console.log(date)
                                    wx.getStorage({
                                        key: 'time',
                                        success: function (res) {
                                            console.log(res)
                                            var getShare = res.data
                                            console.log(getShare, date)
                                            if (date != getShare) {
                                                wx.setStorage({
                                                    key: 'shareNum',
                                                    data: '3'
                                                })
                                                wx.setStorage({
                                                    key: 'time',
                                                    data: date + ''
                                                })
                                            } else {
                                                wx.getStorage({
                                                    key: 'shareNum',
                                                    success: function (res) {
                                                        console.log(res)
                                                    }
                                                })
                                                wx.getStorage({
                                                    key: 'time',
                                                    success: function (res) {
                                                        console.log(res)
                                                    }
                                                })
                                            }
                                        },
                                        fail: function (res) {
                                            wx.setStorage({
                                                key: 'shareNum',
                                                data: '3'
                                            })
                                            wx.setStorage({
                                                key: 'time',
                                                data: date + ''
                                            })

                                        }
                                    })
                                    // 闯关/分享加密提交
                                    if (app.globalData.userInfo) {
                                        var NewTime = new Date().getTime().toString();
                                        console.log(NewTime)
                                        // console.log(app.globalData.userInfo.id + NewTime+app.globalData.userInfo.checkpoint+ app.globalData.userInfo.id)
                                        var key = util.sha1(app.globalData.userInfo.id + NewTime + app.globalData.userInfo.checkpoint + app.globalData.userInfo.id);
                                        console.log(key)
                                        key = key.toUpperCase()
                                        var data = {}
                                        console.log(app.globalData.Sharing)
                                        if (app.globalData.Sharing) {
                                            data = {
                                                key: key,
                                                time: NewTime,
                                                checkpoint: app.globalData.userInfo.checkpoint,
                                                x_token: app.globalData.userInfo.token,
                                                errMsg: app.globalData.Sharing.errMsg,
                                                encryptedData: app.globalData.Sharing.encryptedData,
                                                iv: app.globalData.Sharing.iv,
                                                session_key: app.globalData.session_key
                                            }
                                        } else {
                                            data = {
                                                key: key,
                                                time: NewTime,
                                                checkpoint: app.globalData.userInfo.checkpoint,
                                                x_token: app.globalData.userInfo.token,
                                            }
                                        }

                                        wx.request({
                                            url: 'https://caige1.sanliwenhua.com/caige101/update_checkpoint',
                                            method: "post",
                                            data: data,
                                            success: function (res) {
                                                console.log('keykeykeykeykey', res)
                                                app.globalData.group_id = res.data.group_id
                                            },
                                            fail: function (res) {

                                            }
                                        })
                                    }
                                } else {
                                    console.log(res3.data);
                                }
                            },
                            fail: function (res3) {
                                console.error(res3, '登录失败');
                            }
                        })
                    }
                })
            }
        })
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        var that = this;
        console.log(11547, this.data.avatarUrl)
        wx.getStorage({
            key: 'userInfo',
            success: function (res) {
                console.log('local', res)
                var userInfo = JSON.parse(res.data)
                console.log('5454554', res.data)
                that.setData({
                    avatarUrl: userInfo.avatarUrl,
                    nikename: userInfo.nickName,
                    checkpoint: userInfo.checkpoint,
                    token: userInfo.token
                })
            },
            fail: function (res) {
                console.log(res)
            }
        })
        /*wx.getStorage({
            key: 'userInfo',
            success: function (res) {
                var userInfoLocal = JSON.parse(res.data)
                console.log(userInfoLocal)
                that.setData({
                    avatarUrl: userInfoLocal.avatarUrl
                })
            },
            fail: function (res) {
                console.log('不知为何取不到了，信息在后面', res)
            }
        })*/
        wx.showShareMenu({
            withShareTicket: true
        })
        //console.log(5555, this.fromShareBack)
        //如果是从分享成功进来的
        if (that.fromShareBack && app.globalData.platform == "ios"){
            wx.getShareInfo({
                shareTicket: app.globalData.shareTicket,
                success: function (res) {
                    console.log(res)
                    app.globalData.Sharing = {}
                    app.globalData.Sharing.errMsg = res.errMsg
                    app.globalData.Sharing.encryptedData = res.encryptedData
                    app.globalData.Sharing.iv = res.iv
                    that.updata();
                }
            })
            console.log(app.globalData.Sharing)
            that.fromShareBack = false;

        }
    },
    updata:function () {   // 闯关/分享加密提交获取group_id(群id)
        var that = this
        if (app.globalData.userInfo) {
            var NewTime = new Date().getTime().toString();
            //console.log(NewTime)
            // console.log(app.globalData.userInfo.id + NewTime+app.globalData.userInfo.checkpoint+ app.globalData.userInfo.id)
            var key = util.sha1(app.globalData.userInfo.id + NewTime + app.globalData.userInfo.checkpoint + app.globalData.userInfo.id);
            //console.log(key)
            key = key.toUpperCase()
            var data = {}
            if(app.globalData.shareTicket){
                wx.getShareInfo({
                    shareTicket:app.globalData.shareTicket,
                    success:function (res) {
                        console.log(res)
                        app.globalData.Sharing={}
                        app.globalData.Sharing.errMsg = res.errMsg
                        app.globalData.Sharing.encryptedData = res.encryptedData
                        app.globalData.Sharing.iv = res.iv
                        console.log(app.globalData.Sharing)
                        if (app.globalData.Sharing) {
                            data = {
                                key: key,
                                time: NewTime,
                                checkpoint: app.globalData.userInfo.checkpoint,
                                x_token: app.globalData.userInfo.token,
                                errMsg: app.globalData.Sharing.errMsg,
                                encryptedData: app.globalData.Sharing.encryptedData,
                                iv: app.globalData.Sharing.iv,
                                session_key: app.globalData.session_key
                            }
                        } else {
                            data = {
                                key: key,
                                time: NewTime,
                                checkpoint: app.globalData.userInfo.checkpoint,
                                x_token: app.globalData.userInfo.token,
                            }
                        }
                        wx.request({
                            url: 'https://caige1.sanliwenhua.com/caige101/update_checkpoint',
                            method: "post",
                            data: data,
                            success: function (res1) {
                                //console.log('keykeykeykeykey', res1)
                                if(res1.data.group_id){
                                    app.globalData.group_id = res1.data.group_id;
                                    wx.getStorage({
                                        key: 'userInfo',
                                        success: function (res2) {
                                            //console.log(res.data)
                                            var userInfoLocal = {}
                                            userInfoLocal = JSON.parse(res2.data)
                                            //console.log(userInfoLocal)
                                            userInfoLocal.group_id = res1.data.group_id;
                                            wx.setStorage({
                                                key: 'userInfo',
                                                data: JSON.stringify(userInfoLocal)
                                            })
                                        },
                                        fail: function () {

                                        }
                                    })
                                    that.rankList();
                                }
                            },
                            fail: function (res2) {

                            }
                        })
                    }
                })

            }

        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        clearInterval(this.timeClock)
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function (res) {
        var that = this;
        // _this.data.pic = 'http://p4svid6ld.bkt.clouddn.com/image/zhuanbi.jpg'; //测试修改
        if (res.from === 'button') {
            console.log(res.target)
        }
        return {
            title: '[@我]想要与您进行猜歌挑战，点击进入！',
            path: 'pages/index/index',
            imageUrl: '/image/pc_03.jpg',
            success: function (res) {
                wx.showToast({
                    title: '分享成功!',
                    icon: 'success',
                    duration: 2000
                })
                if(res.shareTickets){
                    console.log('分享到群的标记', res.shareTickets[0])
                    app.globalData.shareTicket = res.shareTickets[0]
                    that.fromShareBack = true;

                    if(app.globalData.platform == "android"){
                        wx.getShareInfo({
                            shareTicket: app.globalData.shareTicket,
                            success: function (res) {
                                console.log(res)
                                app.globalData.Sharing = {}
                                app.globalData.Sharing.errMsg = res.errMsg
                                app.globalData.Sharing.encryptedData = res.encryptedData
                                app.globalData.Sharing.iv = res.iv
                                that.updata();
                            }
                        })
                        console.log(app.globalData.Sharing)
                        that.fromShareBack = false;
                    }
                }

            },
            fail: function (res) {
                wx.showToast({
                    title: '分享失败！',
                    image: '/image/errIcon.png',
                    duration: 2000
                })
            }
        }
    }
})